package com.xyht.sca_s.student_manage_system.modules.teacher.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.PinYinUtil;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgStructure;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgUserRelation;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgStructureMapper;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgUserRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.teacher.entity.SmsTeacherInfo;
import com.xyht.sca_s.student_manage_system.modules.teacher.entity.SmsUserTeacherRelation;
import com.xyht.sca_s.student_manage_system.modules.teacher.entity.req.SmsTeacherInfoAddReq;
import com.xyht.sca_s.student_manage_system.modules.teacher.entity.req.SmsTeacherInfoDeletedReq;
import com.xyht.sca_s.student_manage_system.modules.teacher.entity.req.SmsTeacherInfoUpdateReq;
import com.xyht.sca_s.student_manage_system.modules.teacher.entity.resp.SmsTeacherInfoResp;
import com.xyht.sca_s.student_manage_system.modules.teacher.mapper.SmsTeacherInfoMapper;
import com.xyht.sca_s.student_manage_system.modules.teacher.mapper.SmsUserTeacherRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.teacher.service.SmsTeacherInfoService;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsRole;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUserRoleRelation;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsRoleMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserRoleRelationMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.teacher.constant.ActiveStatusConstant.ACTIVE_STATUS_WORK;
import static com.xyht.sca_s.student_manage_system.modules.teacher.constant.RoleConstant.ROLE_TEACHER;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.TeacherAndStudentFlag.TEACHER_FLAG;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.commonConstant.DEFAULT_PASSWORD;

/**
 * <p>
 * 教师信息表 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2022-12-03
 */
@Service
public class SmsTeacherInfoServiceImpl extends ServiceImpl<SmsTeacherInfoMapper, SmsTeacherInfo> implements SmsTeacherInfoService {

    @Autowired
    private SmsTeacherInfoMapper smsTeacherInfoMapper;
    @Autowired
    private SmsUserMapper smsUserMapper;
    @Autowired
    private SmsUserTeacherRelationMapper userTeacherRelationMapper;
    @Autowired
    private PinYinUtil pinYinUtil;
    @Autowired
    private SmsUserRoleRelationMapper userRoleRelationMapper;
    @Autowired
    private SmsOrgUserRelationMapper orgUserRelationMapper;
    @Autowired
    private SmsOrgStructureMapper smsOrgStructureMapper;
    @Autowired
    private SmsRoleMapper smsRoleMapper;

    @Override
    @Transactional
    public ResponseResult addTeacherInfo(SmsTeacherInfoAddReq addReq) {
        if (isNullOrEmpty(addReq.getTchName(), addReq.getTchTel(), addReq.getTchOrgId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //校验组织是否存在
        Integer orgId = Integer.parseInt(addReq.getTchOrgId());
        SmsOrgStructure orgStructure = smsOrgStructureMapper.selectById(orgId);
        if(isNullOrEmpty(orgStructure)){
            return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
        }
        //组织id
        String orgName = orgStructure.getOrgName();
        //校验是否添加了教师角色
        if (addReq.getTchRoleIdList() == null || addReq.getTchRoleIdList().size() < 1) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        List<String> roleIdList = addReq.getTchRoleIdList();
        if(!roleIdList.contains(ROLE_TEACHER)){
            return CommonResult.failed(CommonCodeEnum.TEACHER_ROLE_NOT);
        }
        //判断角色是否存在
        for (String roleId : roleIdList) {
            SmsRole smsRole = smsRoleMapper.selectById(roleId);
            if(isNullOrEmpty(smsRole)){
                return CommonResult.failed(CommonCodeEnum.ROLE_NOT_EXIST);
            }
        }
        //校验是否存在教师信息
        List<SmsTeacherInfo> smsTeacherInfos = smsTeacherInfoMapper.selectList(new LambdaQueryWrapper<SmsTeacherInfo>()
                .eq(SmsTeacherInfo::getTchTel, addReq.getTchTel()));
        if(smsTeacherInfos != null && smsTeacherInfos.size() > 0){
            return CommonResult.failed(CommonCodeEnum.TEACHER_EXIST);
        }

        //创建教师信息
        SmsTeacherInfo addTeacherInfo = new SmsTeacherInfo();
        BeanUtils.copyProperties(addReq, addTeacherInfo);
        //工号与电话一致
        addTeacherInfo.setTchNo(addReq.getTchTel());
        addTeacherInfo.setTchOrg(orgName);
        addTeacherInfo.setIsAssistant("否");
        //在职状态
        addTeacherInfo.setActiveStatus(ACTIVE_STATUS_WORK);
        smsTeacherInfoMapper.insert(addTeacherInfo);

        String tchId = addTeacherInfo.getId();

        //创建用户信息
        SmsUser addUser = new SmsUser();
        addUser.setFlag(TEACHER_FLAG);
        addUser.setPassword(DEFAULT_PASSWORD);
        addUser.setRealName(addTeacherInfo.getTchName());
        addUser.setUsername(addTeacherInfo.getTchNo());
        addUser.setTel(addTeacherInfo.getTchTel());
        smsUserMapper.insert(addUser);

        String userId = addUser.getId();

        //创建教师和用户信息
        SmsUserTeacherRelation addUserTeacherRelation = new SmsUserTeacherRelation();
        addUserTeacherRelation.setUserId(userId);
        addUserTeacherRelation.setTchId(tchId);
        userTeacherRelationMapper.insert(addUserTeacherRelation);

        //创建用户与组织信息
        SmsOrgUserRelation addOrgUserRelation = new SmsOrgUserRelation();
        addOrgUserRelation.setUserId(userId);
        addOrgUserRelation.setOrgId(orgId.toString());
        orgUserRelationMapper.insert(addOrgUserRelation);

        //创建用户和角色的信息
        for (String roleId : roleIdList) {
            SmsUserRoleRelation addUserRoleRelation = new SmsUserRoleRelation();
            addUserRoleRelation.setUserId(userId);
            addUserRoleRelation.setRoleId(roleId);
            userRoleRelationMapper.insert(addUserRoleRelation);
        }

        return CommonResult.success();
    }

    @Override
    public ResponseResult getTeacherInfoList(Integer pageSize, Integer pageNum, String search) {
        Page<SmsTeacherInfo> page =  new Page<>(pageNum,pageSize);
        List<SmsTeacherInfoResp> teacherInfoList;
        LambdaQueryWrapper<SmsTeacherInfo> queryWrapper = new LambdaQueryWrapper<>();
        if(!isNullOrEmpty(search)){
            queryWrapper.like(SmsTeacherInfo::getTchName,search)
            .or()
            .like(SmsTeacherInfo::getTchTel,search);
        }
        queryWrapper.orderByDesc(SmsTeacherInfo::getCreateTime);
        smsTeacherInfoMapper.selectPage(page,queryWrapper);
        teacherInfoList = page.getRecords()
                .stream()
                .map(smsTeacherInfo -> {
                    SmsTeacherInfoResp smsTeacherInfoResp = new SmsTeacherInfoResp();
                    BeanUtils.copyProperties(smsTeacherInfo,smsTeacherInfoResp);
                    if(!isNullOrEmpty(smsTeacherInfo)) {
                        String nameSpell = pinYinUtil.getHanZiPY(smsTeacherInfo.getTchName());//名字转拼音
                        smsTeacherInfoResp.setTchNameSpell(nameSpell);
                    }
                    return smsTeacherInfoResp;
                })
                .collect(Collectors.toList());
        int total = (int) page.getTotal();
        return CommonResult.success(teacherInfoList,total);
    }

    @Override
    public ResponseResult getTeacherInfoDetail(String tchId) {
        if (isNullOrEmpty(tchId)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsTeacherInfo teacherInfo = smsTeacherInfoMapper.selectById(tchId);
        if(teacherInfo == null){
            return CommonResult.failed(CommonCodeEnum.TEACHER_NOT_EXIST);
        }
        SmsTeacherInfoResp smsTeacherInfoResp = new SmsTeacherInfoResp();
        BeanUtils.copyProperties(teacherInfo,smsTeacherInfoResp);
        if(!isNullOrEmpty(teacherInfo)) {
            String nameSpell = pinYinUtil.getHanZiPY(teacherInfo.getTchName());//名字转拼音
            smsTeacherInfoResp.setTchNameSpell(nameSpell);
        }
        return CommonResult.success(smsTeacherInfoResp);
    }

    @Override
    @Transactional
    public ResponseResult updateTeacherInfo(SmsTeacherInfoUpdateReq updateReq) {
        if (isNullOrEmpty(updateReq.getId(), updateReq.getTchNo(), updateReq.getTchName(),
                updateReq.getTchTel(), updateReq.getTchOrg(), updateReq.getIsAssistant())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsTeacherInfo teacherInfo = smsTeacherInfoMapper.selectById(updateReq.getId());
        if(teacherInfo == null){
            return CommonResult.failed(CommonCodeEnum.TEACHER_NOT_EXIST);
        }
        String updateTchNo = updateReq.getTchNo();
        String updateTchTel = updateReq.getTchTel();
        String tchNo = teacherInfo.getTchNo();
        String tchTel = teacherInfo.getTchTel();
        //校验教师信息中工号修改了原工号并且不可重复
        if(!tchNo.equals(updateTchNo)) {
            List<SmsTeacherInfo> smsTeacherInfoByNo = smsTeacherInfoMapper.selectList(new LambdaQueryWrapper<SmsTeacherInfo>()
                    .eq(SmsTeacherInfo::getTchNo, updateReq.getTchNo()));
            if (smsTeacherInfoByNo != null && smsTeacherInfoByNo.size() > 0) {
                return CommonResult.failed(CommonCodeEnum.USER_ACCOUNT_EXIST);
            }
        }
        //校验教师信息中电话号码修改了原号码并且不可重复
        if(!tchTel.equals(updateTchTel)) {
            List<SmsTeacherInfo> smsTeacherInfoByTel = smsTeacherInfoMapper.selectList(new LambdaQueryWrapper<SmsTeacherInfo>()
                    .eq(SmsTeacherInfo::getTchTel, updateReq.getTchTel()));
            if (smsTeacherInfoByTel != null && smsTeacherInfoByTel.size() > 0) {
                return CommonResult.failed(CommonCodeEnum.TEL_EXIST);
            }
        }
        //通过教师用户关系表查询用户id
        SmsUserTeacherRelation userTeacherRelation = userTeacherRelationMapper.selectList(new LambdaQueryWrapper<SmsUserTeacherRelation>()
                .eq(SmsUserTeacherRelation::getTchId, updateReq.getId())).get(0);
        if (userTeacherRelation == null) {
            return CommonResult.failed(CommonCodeEnum.TEACHER_USER_RELATION_NOT_EXIST);
        }
        String userId = userTeacherRelation.getUserId();
        //查询用户信息
        SmsUser smsUser = smsUserMapper.selectById(userId);
        if(smsUser == null){
            return CommonResult.failed(CommonCodeEnum.USER_NOT_EXIST);
        }
        String username = smsUser.getUsername();
        String tel = smsUser.getTel();
        //校验用户表中用户了原用户并且不可重复
        if(!username.equals(updateTchNo)) {
            List<SmsUser> smsUsersByUserName = smsUserMapper.selectList(new LambdaQueryWrapper<SmsUser>()
                    .eq(SmsUser::getUsername, updateReq.getTchNo()));
            if (smsUsersByUserName != null && smsUsersByUserName.size() > 0) {
                return CommonResult.failed(CommonCodeEnum.USER_ACCOUNT_EXIST);
            }
        }
        //校验用户表中电话号码修改了原号码并且不可重复
        if(!tel.equals(updateTchTel)) {
            List<SmsUser> smsUsersByTel = smsUserMapper.selectList(new LambdaQueryWrapper<SmsUser>()
                    .eq(SmsUser::getTel, updateReq.getTchTel()));
            if (smsUsersByTel != null && smsUsersByTel.size() > 0) {
                return CommonResult.failed(CommonCodeEnum.TEL_EXIST);
            }
        }
        //修改教师信息
        BeanUtils.copyProperties(updateReq,teacherInfo);
        smsTeacherInfoMapper.updateById(teacherInfo);
        //修改用户信息
        smsUser.setFlag(TEACHER_FLAG);
        smsUser.setPassword(DEFAULT_PASSWORD);
        smsUser.setRealName(teacherInfo.getTchName());
        smsUser.setTel(updateTchTel);
        smsUser.setUsername(updateTchNo);
        smsUserMapper.updateById(smsUser);

        return CommonResult.success();
    }

    @Override
    @Transactional
    public ResponseResult deletedTeacherInfo(SmsTeacherInfoDeletedReq deletedReq) {
        if (isNullOrEmpty(deletedReq.getTchId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsTeacherInfo teacherInfo = smsTeacherInfoMapper.selectById(deletedReq.getTchId());
        if (teacherInfo == null) {
            return CommonResult.failed(CommonCodeEnum.TEACHER_NOT_EXIST);
        }
        SmsUserTeacherRelation userTeacherRelation = userTeacherRelationMapper.selectList(new LambdaQueryWrapper<SmsUserTeacherRelation>()
                .eq(SmsUserTeacherRelation::getTchId, deletedReq.getTchId())).get(0);
        if (userTeacherRelation == null) {
            return CommonResult.failed(CommonCodeEnum.TEACHER_USER_RELATION_NOT_EXIST);
        }
        SmsUser smsUser = smsUserMapper.selectById(userTeacherRelation.getUserId());
        if(smsUser == null){
            return CommonResult.failed(CommonCodeEnum.USER_NOT_EXIST);
        }
        userTeacherRelationMapper.deleteById(userTeacherRelation.getId());
        smsUserMapper.deleteById(smsUser.getId());
        smsTeacherInfoMapper.deleteById(deletedReq.getTchId());
        return CommonResult.success();
    }
}
